import 'dart:async';
import 'dart:io';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/ext/widget_extension.dart';
import 'package:enterprise_v6_app/app/data/api/file_upload_apis.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:lottie/lottie.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

/// 录音
/// [onCallBack] 录音地址回调
class CustomTapeSheet extends StatefulWidget {
  const CustomTapeSheet({required this.onCallBack, super.key});

  final Function(String url) onCallBack;

  @override
  State<CustomTapeSheet> createState() => _CustomTapeSheetState();
}

class _CustomTapeSheetState extends State<CustomTapeSheet> {
  StreamSubscription? _recorderSubscription;
  StreamSubscription? _recordingDataSubscription;
  StreamController<Food>? recordingDataController;
  final Codec _codec = Codec.aacMP4;
  IOSink? sink;

  /// Sample rate used for Streams
  int tSTREAMSAMPLERATE = 44000;

  // 录音
  final FlutterSoundRecorder recorderModule = FlutterSoundRecorder();

  // 录音时间
  String _recorderTxt = '00:00:00';

  // 录音路径
  String _tapePath = '';

  // 录音状态
  bool _isRecording = false;

  @override
  void initState() {
    super.initState();
    // 权限请求
    requestAudioPermission();
    _initializeExample();
  }

  @override
  void dispose() {
    super.dispose();
    releaseFlauto();
  }

  /// 权限请求
  Future<void> requestAudioPermission() async {
    // 检查是否已经授予录音权限
    var status = await Permission.microphone.status;
    if (status.isGranted) {
      return;
    } else if (status.isDenied) {
      // 如果权限被拒绝，请求权限
      status = await Permission.microphone.request();
    }
    // 根据请求权限后的状态处理
    if (status.isGranted) {
      // 权限被授予
      return;
    } else if (status.isPermanentlyDenied) {
      // 权限被永久拒绝，通常需要引导用户打开应用设置页面手动授予权限
      openAppSettings();
    } else {
      Get.back();
    }
  }

  /// 初始化
  Future<void> _initializeExample() async {
    // 开启
    await recorderModule.openRecorder();
    // 设置向持续时间侦听器发送持续时间更新的频率
    await recorderModule.setSubscriptionDuration(const Duration(milliseconds: 10));
  }

  /// 释放
  Future<void> releaseFlauto() async {
    try {
      if (_isRecording) {
        stopRecorder();
      }
      await recorderModule.closeRecorder();
    } on Exception {
      recorderModule.logger.e('Released unsuccessful');
    }
  }

  /// 开启、关闭
  void startStopRecorder() {
    if (recorderModule.isRecording || recorderModule.isPaused) {
      stopRecorder();
    } else {
      startRecorder();
    }
  }

  /// 开启录音
  void startRecorder() async {
    try {
      // 替换为你要保存的文件路径
      final Directory directory = await getApplicationDocumentsDirectory();
      _tapePath = '${directory.path}/flutter_sound${ext[_codec.index]}';
      await recorderModule.startRecorder(
        toFile: _tapePath,
        codec: _codec,
        // bitRate: 8000,
        // numChannels: 1,
        // sampleRate: tSTREAMSAMPLERATE,
      );
      _recorderSubscription = recorderModule.onProgress!.listen((e) {
        if (mounted) {
          setState(() {
            _recorderTxt = formatMilliseconds(e.duration.inMilliseconds);
          });
        }
      });

      setState(() {
        _isRecording = true;
      });
    } on Exception catch (err) {
      recorderModule.logger.e('startRecorder error: $err');
      setState(() {
        stopRecorder();
        _isRecording = false;
        cancelRecordingDataSubscription();
        cancelRecorderSubscriptions();
      });
    }
  }

  /// 将毫秒转为00:00:00格式
  String formatMilliseconds(int milliseconds) {
    final Duration duration = Duration(milliseconds: milliseconds);
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final String twoDigitHours = twoDigits(duration.inHours);
    final String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
    final String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));

    return '$twoDigitHours:$twoDigitMinutes:$twoDigitSeconds';
  }

  void stopRecorder() async {
    try {
      await recorderModule.stopRecorder();
      recorderModule.logger.d('stopRecorder');
      cancelRecorderSubscriptions();
      cancelRecordingDataSubscription();
    } on Exception catch (err) {
      recorderModule.logger.d('stopRecorder error: $err');
    }
    setState(() {
      _isRecording = false;
    });
  }

  void cancelRecorderSubscriptions() {
    if (_recorderSubscription != null) {
      _recorderSubscription!.cancel();
      _recorderSubscription = null;
    }
  }

  void cancelRecordingDataSubscription() {
    if (_recordingDataSubscription != null) {
      _recordingDataSubscription!.cancel();
      _recordingDataSubscription = null;
    }
    recordingDataController = null;
    if (sink != null) {
      sink!.close();
      sink = null;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 440.w,
      alignment: Alignment.center,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(20.w)),
          gradient: const LinearGradient(
              //渐变位置
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              //渐变颜色[始点颜色, 结束颜色]
              colors: [Color(0xffE7EAFF), Colors.white, Colors.white])),
      child: Stack(
        alignment: Alignment.center,
        children: [
          Visibility(
            visible: _isRecording,
            child: SizedBox(
                child: Lottie.asset(
                    'assets/lottie/sound.json',
                    width: AppDimens.sw - 50,
                    fit: BoxFit.cover,
                )),
          ),
          Column(
            children: [
              AppGaps.vGap20,
              Container(
                padding: EdgeInsets.symmetric(horizontal: 20.w),
                child: Row(
                  children: [
                    SizedBox(width: 24.w),
                    Expanded(
                      child: Text(
                        '录音',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                            fontSize: 18.sp,
                            height: 1.2,
                            color: const Color(0xFF262626),
                            fontWeight: FontWeight.w500),
                      ),
                    ),
                    SvgPicture.asset(
                      AppImages.icon_delete,
                      width: 24.w,
                      height: 24.w,
                      colorFilter: const ColorFilter.mode(Color(0xFFA0A7B5), BlendMode.srcIn),
                    ).clickOnce(Get.back)
                  ],
                ),
              ),
              AppGaps.vGap50,
              Text(
                _recorderTxt,
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: 36.sp,
                  height: 1.2,
                  color: const Color(0xFF5C6DFF),
                  fontWeight: FontWeight.w400,
                ),
              ),
              AppGaps.vGap30,
              Image.asset(
                AppImages.icon_tape_blue,
                height: 100.w,
                width: 100.w,
              ).clickOnce(() async {
                // 申请麦克风权限
                await [
                  Permission.microphone,
                ].request();
                startStopRecorder();
              }),
              AppGaps.vGap20,
              Text(
                _tapePath.isEmpty ? '- -点击录音- -' : (_isRecording ? '- -录音中- -' : '- -重新录制- -'),
                style: TextStyle(
                  fontSize: 14.sp,
                  height: 1.2,
                  color: const Color(0xFF262F38),
                  fontWeight: FontWeight.w500,
                ),
              ),
              AppGaps.vGap30,
              // Container(
              //   padding: EdgeInsets.symmetric(horizontal: 40.w),
              //   child: Row(
              //     mainAxisAlignment: MainAxisAlignment.spaceBetween,
              //     children: [
              //       SizedBox(
              //         width: 40.w,
              //       ),
              //       Icon(
              //         Icons.play_circle,
              //         color: const Color(0xFF5C6DFF),
              //         size: 48.w,
              //       ),
              //       SvgPicture.asset(
              //         AppImages.icon_select,
              //         width: 40.w,
              //         height: 40.w,
              //       )
              //     ],
              //   ),
              // ),
              Visibility(
                visible: _tapePath.isNotEmpty && !_isRecording,
                child: SvgPicture.asset(
                  AppImages.icon_select,
                  width: 40.w,
                  height: 40.w,
                ).clickOnce(() async {
                  if (_tapePath.isEmpty) {
                    AppToast.showWarning('请录音后提交!');
                    return;
                  }
                  final url = await FileUploadApis.uploadFile(fileUrl: _tapePath);
                  if (url != '') {
                    widget.onCallBack(url);
                    Get.back();
                  } else {
                    AppToast.showWarning('上传失败');
                  }
                }),
              )
            ],
          ),
        ],
      ),
    );
  }
}
